package com.eightbears.beboy.ui.user.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.AgencyCityAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.cache.MyAddressCache;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PutFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.citypicker.model.City;
import com.eightbears.beboy.base.view.popupwindow.AgencyCityPopup;
import com.eightbears.beboy.entity.FollowEntity;
import com.eightbears.beboy.entity.PutAdaminEntity;
import com.eightbears.beboy.entity.StaticDataEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.UserStatisticEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.greendao.District;
import com.eightbears.greendao.Friends;
import com.eightbears.greendao.MyAddress;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_USER_ID;
import static com.eightbears.beboy.base.util.CommonAPI.URL_ADAMINUPDATE_USER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FOLLOW_UNFOLLOW;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_USERDATA;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USER_STATISTIC;

/**
 * 用户个人信息
 */
public class UserInfoActivity extends BaseActivity {

    public static final String PARAMS_USER_INFO = "userInfo";
    public static final String STATUS_IS_ADMIN = "1";
    public static final String STATUS_IS_NOT_ADMIN = "0";

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_level)
    ImageView iv_level;
    @BindView(R.id.iv_vip)
    ImageView iv_vip;

    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R.id.tv_follow)
    TextView tv_follow;
    @BindView(R.id.tv_fans)
    TextView tv_fans;
    @BindView(R.id.tv_follow_icon)
    TextView tv_follow_icon;
    @BindView(R.id.tv_chat_icon)
    TextView tv_chat_icon;
    @BindView(R.id.iv_head)
    RoundedImageView iv_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.tv_birthday)
    TextView tv_birthday;
    @BindView(R.id.tv_weichat)
    TextView tv_weichat;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.ll_other_user)
    LinearLayout ll_other_user;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.ll_user_agency)
    LinearLayout ll_user_agency;
    @BindView(R.id.tv_agency_city)
    TextView tv_agency_city;
    @BindView(R.id.tb_user_authenticatio)
    ToggleButton tb_user_authenticatio;
    @BindView(R.id.rl_user_authentication)
    RelativeLayout rl_user_authentication;

    private UserEntity selfInfoEntity;
    private UserInfoEntity mUserInfoEntity;
    private UserStatisticEntity userStatisticEntity;
    private AgencyCityAdapter mAgencyCityAdapter;
    private AgencyCityPopup mAgencyCityPopup;

    private String username;
    private String districtId;
    private String authParam = STATUS_IS_ADMIN;
    private String mCityId;
    private ArrayList<City> mCities = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(getText(R.string.text_userinfo));
    }

    @Override
    protected void initData() {
        selfInfoEntity = SPUtil.getUser();
        username = getIntent().getStringExtra(PARAMS_USER_INFO);
        initCityPopup();
        getUserInfo();
    }


    @Override
    protected void initEvent() {
        //侧滑
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        tb_user_authenticatio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    authParam = "1";
                    postAdamin();
                } else {
                    authParam = "0";
                    postAdamin();
                }
            }
        });

        mAgencyCityAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.ll_item_popup:
                        if (position == 1) {
                            tv_agency_city.setText("无");
                            mAgencyCityPopup.dismiss();
                        } else {
                            tv_agency_city.setText(((City) adapter.getData().get(position)).getName());
                            mCityId = DistrictCache.getInstance(mContext).getCacheByName(((City) adapter.getData().get(position)).getName()).getId();
                        }
                        postAdamin();
                        mAgencyCityPopup.dismiss();
                        break;
                }
            }
        });

    }

    private void initCityPopup() {
        mAgencyCityAdapter = new AgencyCityAdapter(mContext);
        mAgencyCityPopup = new AgencyCityPopup(this);
        mAgencyCityPopup.setTitle("代理城市");
        getDistrictData();
    }

    private void setUserPower() {

        if (selfInfoEntity.getData().getIs_admin().equals(STATUS_IS_ADMIN)) {
            if (mUserInfoEntity.getData().getIs_admin().equals(STATUS_IS_NOT_ADMIN)) {
                ll_user_agency.setVisibility(View.VISIBLE);
            }
        } else if (selfInfoEntity.getData().getIs_agent().equals(STATUS_IS_ADMIN)) {

            if (!mUserInfoEntity.getData().getIs_admin().equals(STATUS_IS_NOT_ADMIN) &&
                    !mUserInfoEntity.getData().getIs_agent().equals(STATUS_IS_ADMIN) &&
                    mUserInfoEntity.getData().getMobile_city_id().equals(selfInfoEntity.getData().getAgent_city_id())) {
                ll_user_agency.setVisibility(View.VISIBLE);
                rl_user_authentication.setVisibility(View.GONE);
            }
        }

        if (mUserInfoEntity.getData().getVip_level() == 1) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip1);
        } else if (mUserInfoEntity.getData().getVip_level() == 2) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip2);
        } else {
            iv_vip.setVisibility(View.GONE);
        }

        if (mUserInfoEntity.getData().getPoints() != null) {
            if (mUserInfoEntity.getData().getPoints().getLevel() == 1) {
                iv_level.setImageResource(R.mipmap.icon_level_one);
            } else if (mUserInfoEntity.getData().getPoints().getLevel() == 2) {
                iv_level.setImageResource(R.mipmap.icon_level_two);
            } else if (mUserInfoEntity.getData().getVip_level() == 3) {
                iv_level.setImageResource(R.mipmap.icon_level_three);
            } else if (mUserInfoEntity.getData().getVip_level() == 4) {
                iv_level.setImageResource(R.mipmap.icon_level_four);
            } else if (mUserInfoEntity.getData().getVip_level() == 5) {
                iv_level.setImageResource(R.mipmap.icon_level_five);
            }
            iv_level.setVisibility(View.VISIBLE);
        }

    }

    @OnClick(R.id.rl_agency_city)
    void agency_city() {
        mAgencyCityPopup.showPopupWindow();
    }

    /**
     * 获取用户数据
     */
    public void getUserInfo() {
        OkHttpUtils.get().url(URL_RESET_USERDATA + username)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                mUserInfoEntity = GsonUtil.fromJson(response, UserInfoEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(mUserInfoEntity.getStatus_code() + "")) {
                    setUserPower();
                    getUserData();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(UserInfoActivity.this, status_error);
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.ll_userpublish)
    void viewPublish() {
        startLocalActivity(this, UserPublishInfo.class, PARAMS_USER_ID, username);
    }


    /**
     * 用户关注等信息
     */
    private void getUserData() {
        String url = URL_USER_STATISTIC + username + "/statistic";
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                userStatisticEntity = GsonUtil.fromJson(response, UserStatisticEntity.class);
                if (userStatisticEntity.getStatus_code().equals(String.valueOf(CONNECTION_STATUS_SUCCESS))) {
                    setUserData();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(UserInfoActivity.this, status_error);
            }
        });
    }

    private void getDistrictData() {
        mCities.clear();
        StaticDataEntity staticData = SPUtil.getStaticData();
        List<StaticDataEntity.Districts> public_districts = staticData.getData().getPublic_districts();
        for (int i = 0; i < public_districts.size(); i++) {
            if (DistrictCache.getInstance(mContext).getCacheById(String.valueOf(public_districts.get(i).getId())).getType().equals(String.valueOf(2))) {
                City city = new City();
                city.setName(DistrictCache.getInstance(mContext).getCacheById(String.valueOf(public_districts.get(i).getId())).getName());
                mCities.add(city);
            }
        }
        City city1 = new City();
        city1.setName("无");
        mCities.add(0, city1);
        mAgencyCityAdapter.setNewData(mCities);
        mAgencyCityPopup.setListViewAdapter(mAgencyCityAdapter);
    }


    public void postAdamin() {
        PutFormBuilder builder = OkHttpUtils.put().url(URL_ADAMINUPDATE_USER + mUserInfoEntity.getData().getUser_id() + "/adminEdit");
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());

        if (mUserInfoEntity.getData().getIs_admin().equals(STATUS_IS_ADMIN)) {
            builder.addParams("auth", authParam);
        } else if ((mUserInfoEntity.getData().getIs_agent().equals(STATUS_IS_ADMIN))) {
            builder.addParams("agent", "1");
        }
        if (mCityId != null)
            builder.addParams("agent_city_id", mCityId);
        builder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                PutAdaminEntity putAdaminEntity = GsonUtil.fromJson(response, PutAdaminEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(putAdaminEntity.getStatus_code() + "")) {
                    if (putAdaminEntity.getData().getIs_auth() == 1) {
                        tb_user_authenticatio.setChecked(true);
                    } else {
                        tb_user_authenticatio.setChecked(false);
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(UserInfoActivity.this, status_error);
            }
        });
    }

    /**
     * 关注
     */
    @OnClick(R.id.ll_follow)
    void follow() {
        exquteFollow();
    }

    /**
     * 跳转到聊天页面
     */
    @OnClick(R.id.ll_chat)
    void chat() {
        if (tv_chat_icon.getText().toString().equals("发送消息")) {
            startLocalActivity(this, ChatActivity.class, "userId", username);
        } else {
            try {
                String s = getResources().getString(R.string.Add_a_friend);
                String s1 = getResources().getString(R.string.send_successful);
                Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_LONG).show();
                EMClient.getInstance().contactManager().addContact(username + "", s);
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        }
    }


    private void setUserData() {
        String cover, nickname, followsNum, fansNum, username, sex, birthday, location;
        if (checkIsSelf()) {
            cover = selfInfoEntity.getData().getCover();
            nickname = selfInfoEntity.getData().getNickname();
            username = selfInfoEntity.getData().getUser_id();
            sex = selfInfoEntity.getData().getSex();
            birthday = selfInfoEntity.getData().getBirthday();
            ll_other_user.setVisibility(View.VISIBLE);
            String wechatBind = selfInfoEntity.getData().getThird_party();
            if (wechatBind.equals("1")) {
                tv_weichat.setText(getString(R.string.text_wechat_bind));
            } else {
                tv_weichat.setText(getString(R.string.text_wechat_no_bind));
            }
            MyAddress myAddress = MyAddressCache.getInstance(this).getData();
            if (null != myAddress) {
                tv_address.setText(myAddress.getAddress());
            } else {
                tv_address.setText(R.string.text_unknown);
            }
            districtId = selfInfoEntity.getData().getDistrict_id();
        } else {
            ll_other_user.setVisibility(View.GONE);
            cover = mUserInfoEntity.getData().getCover();
            nickname = mUserInfoEntity.getData().getNickname();
            mUserInfoEntity.getData().getDistrict_id();
            username = mUserInfoEntity.getData().getUser_id();
            sex = mUserInfoEntity.getData().getSex();
            birthday = mUserInfoEntity.getData().getBirthday();
            districtId = mUserInfoEntity.getData().getDistrict_id();
            setBottomInfo();
        }
        followsNum = userStatisticEntity.getData().getFollow();
        fansNum = userStatisticEntity.getData().getFollower();
        CommonUtils.loadImageView(this, cover, R.mipmap.default_head, iv_head);
        setUserLocation();
        tv_nickname.setText(nickname);
        tv_follow.setText(followsNum);
        tv_fans.setText(fansNum);
        tv_username.setText(username);
        tv_sex.setText(sex);
        tv_birthday.setText(birthday);
    }

    private boolean checkIsSelf() {
        if (username.equals(selfInfoEntity.getData().getUser_id())) {
            return true;
        }
        return false;
    }

    private void setUserLocation() {
        String fullAddress;
        if (TextUtils.isEmpty(districtId)) {
            fullAddress = getString(R.string.text_unknown);
        } else {
            District district = DistrictCache.getInstance(this).getCacheById(districtId);
            District city = DistrictCache.getInstance(this).getCacheById(district.getParent_id());
            District province = DistrictCache.getInstance(this).getCacheById(city.getParent_id());
            String districtName = district.getName();
            String cityName = city.getName();
            String provinceName = province.getName();
            fullAddress = provinceName + " " + cityName + " " + districtName;
        }
        tv_location.setText(fullAddress);
    }

    private void exquteFollow() {
        String url = URL_FOLLOW_UNFOLLOW + username;
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("id", username + "")
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                FollowEntity followEntity = GsonUtil.fromJson(response, FollowEntity.class);
                if (followEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    if (followEntity.getData().getStatus().equals("1")) {
                        Drawable nav_up = getResources().getDrawable(R.mipmap.quxiaoguanzhu);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                        tv_follow_icon.setCompoundDrawables(nav_up, null, null, null);
                        tv_follow_icon.setCompoundDrawablePadding(30);
                        tv_follow_icon.setText("取消关注");
                    } else {
                        Drawable nav_up = getResources().getDrawable(R.mipmap.guanzhu);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                        tv_follow_icon.setCompoundDrawables(nav_up, null, null, null);
                        tv_follow_icon.setCompoundDrawablePadding(30);
                        tv_follow_icon.setText("关注");
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(UserInfoActivity.this, status_error);
            }
        });
    }


    private void setBottomInfo() {
        tv_fans.setText(userStatisticEntity.getData().getFollower());
        tv_follow.setText(userStatisticEntity.getData().getFollow());
        if (userStatisticEntity.getData().getIs_follow().equals("1")) {
            Drawable nav_up = getResources().getDrawable(R.mipmap.quxiaoguanzhu);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            tv_follow_icon.setCompoundDrawables(nav_up, null, null, null);
            tv_follow_icon.setCompoundDrawablePadding(30);
            tv_follow_icon.setText(getString(R.string.text_cancel_follow));
        } else {
            Drawable nav_up = getResources().getDrawable(R.mipmap.guanzhu);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            tv_follow_icon.setCompoundDrawables(nav_up, null, null, null);
            tv_follow_icon.setCompoundDrawablePadding(30);
            tv_follow_icon.setText(getString(R.string.text_aread_follow));
        }

        Friends friends = FriendsCache.getInstance(UserInfoActivity.this).getCacheById(username + "");
        if (friends == null) {
            Drawable nav_up = getResources().getDrawable(R.mipmap.tianjiahaoyou);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            tv_chat_icon.setCompoundDrawables(nav_up, null, null, null);
            tv_chat_icon.setCompoundDrawablePadding(30);
            tv_chat_icon.setText(R.string.text_add);
        } else {
            Drawable nav_up = getResources().getDrawable(R.mipmap.liaotian);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            tv_chat_icon.setCompoundDrawables(nav_up, null, null, null);
            tv_chat_icon.setCompoundDrawablePadding(30);
            tv_chat_icon.setText(R.string.text_send_message);
        }

        ll_bottom.setVisibility(View.VISIBLE);
    }
}
